<?php

use Elasticsearch\ClientBuilder as ElasticsearchClient;
use Handlers\YopurmaqInformationHandler;

require_once __DIR__ . '/vendor/autoload.php';

ini_set('memory_limit', -1);

// 解析命令行参数
$_options = getopt("e:f");

$excepts = [];
if (count($_options) > 0) {
  $excepts = isset($_options['e']) ? explode(',', $_options['e']) : [];
}

$config = require_once __DIR__ . '/configs/config.php';

$instanceConfig = require_once __DIR__ . '/configs/yopurmaqInformation.php';

$dsn = $instanceConfig['database']['dsn'];
$user = $instanceConfig['database']['user'];
$password = $instanceConfig['database']['password'];

$dc = new Nette\Database\Connection($dsn, $user, $password);

$handler = new YopurmaqInformationHandler($instanceConfig['elasticsearch']['hosts'], null);

function bulk_insert_information($connect, $handler, $excepts = []) {
  
  $startTime = microtime(true);

  $categories = $connect->fetchAll("SELECT id, parent_id FROM categorys ORDER BY id");
  
  // 转换为树结构，可以得到一级栏目，只有一级栏目才会建表
  $categories = build_tree($categories);

  foreach ($categories as $cate) {

    $tableStartTime = microtime(true);

    $tableId = $cate['id'];
    $table = 'information_' . $tableId;
    if (in_array((string)$tableId, $excepts)) {
      echo "跳过表{$table}", PHP_EOL;
      continue;
    }

    $table_exists = $connect->fetchField(" SELECT table_name FROM information_schema.tables WHERE table_schema = 'yopurmaq' AND table_name = '{$table}'");
    if (!$table_exists) {
      continue;
    }

    echo "开始同步{$table}", PHP_EOL;

    $perPage = 1000;
    $total = $connect->fetchField("select count(*) as count from {$table}");
    $totalPage = ceil($total / $perPage);

    echo "{$table}表信息总数：", $total, ', 总页数：', $totalPage, PHP_EOL;

    echo "开始获取{$table}表数据...", PHP_EOL;

    // 判断individual_member_id属性是否存在
    $individual_member_id_field = $handler->getIndividualMemberIdField($tableId);

    for ($curPage = 1;$curPage <= $totalPage;$curPage++) {
      $offset = ($curPage - 1) * $perPage;

      echo "{$table}当前页：", $curPage . '/' . $totalPage, ', 偏移量: ', $offset, PHP_EOL;

$sql = <<<EOD
SELECT 
i.id AS id, 
i.uuid AS uuid, 
category_id, 
district_id, 
title, 
thumb, 
video, 
updated_at, 
{$individual_member_id_field}
ic.content AS content
FROM {$table} AS i
JOIN information_content AS ic ON i.uuid = ic.uuid 
ORDER BY i.id
LIMIT ?, ?
EOD;

      $rows = $connect->fetchAll($sql, $offset, $perPage);

      $totalCount = count($rows);
      
      echo "{$table}当前获取数量：", $totalCount, PHP_EOL;

      foreach ($rows as $row) {
        $row = (array)$row;
        $row = $handler->formatMysqlData($row);

        $handler->insertOrUpdate($row, $tableId, true);
      }

      unset($rows);

      echo '当前使用内存：', memory_get_usage(), PHP_EOL;
    }

    $tableEndTime = microtime(true);
    $tableRunTime = gmdate("H:i:s", $tableEndTime - $tableStartTime);

    echo "{$table}表数据获取完毕！花费: ", $tableRunTime, PHP_EOL;
  }

  $endTime = microtime(true);
  $runTime = gmdate("H:i:s", $endTime - $startTime);

  echo "所有information表获取完毕！共花费: ", $runTime, PHP_EOL;
}

bulk_insert_information($dc, $handler, $excepts);



